package com.pachong.controller;

import com.pachong.pojo.MyLikeNews;
import com.pachong.pojo.PaChong;
import com.pachong.pojo.User;
import com.pachong.service.MyLikeNewsServiceImpl;
import com.pachong.service.PaChongServiceImpl;
import com.pachong.unti.PageBean;
import com.pachong.unti.PureNetUtil;
import com.pachong.unti.ReturnDatas;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2018/4/9 0009.
 */
@Controller
@RequestMapping("/pachong")
public class PaChongController  {
@Resource
private PaChongServiceImpl paChongService;
@Resource
private MyLikeNewsServiceImpl myLikeNewsService;
    @RequestMapping("/test")
    public @ResponseBody ReturnDatas test(PaChong record, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest){
        ReturnDatas returnDatas=ReturnDatas.getSuccessReturnDatas();
        try {


            String underUrl="http://www.zut.edu.cn/info/1041/19634.htm";
            Document docNewsLook = Jsoup.parse(PureNetUtil.get(underUrl));
            String content = docNewsLook.getElementById("vsb_content_502").text();         ;
            System.out.println("----------------------"+content);

        }catch (Exception e){
            e.printStackTrace();
        }
        return returnDatas;
    }


    @RequestMapping("/news")
    public @ResponseBody ReturnDatas news(PaChong record, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest){
        ReturnDatas returnDatas=ReturnDatas.getSuccessReturnDatas();
        try {
            Integer pageCount =0;
            String url="http://www.zut.edu.cn";
            String urls="http://www.zut.edu.cn/index";
            String newsUrl="http://www.zut.edu.cn/";
            String flag="";
            // 获取首页的子网页的url
            Document doc = Jsoup.parse(PureNetUtil.get(url));
            Elements eles = doc.select(".bt em a");
            for(int i=0;i<eles.size();i++){
                if(i==0){
                    String urlResult=eles.attr("href");

                    flag=urlResult.split("/")[1].split(".htm")[0];
                    newsUrl=newsUrl+urlResult;
                }else if(i==1){
                    eles.attr("href");
                }else if(i==2){
                    eles.attr("href");
                }
            }
            // 获取新闻子网页列表的每一个详情的url
            Document docNews = Jsoup.parse(PureNetUtil.get(newsUrl));
            // 找到页码
            Elements elesPage = docNews.select("#fanye67214");
            // 解析页码
            String page=elesPage.text().toString().split("共")[1];
            String pageCounts=page.split("条")[0];
            pageCount=Integer.valueOf(pageCounts);
            //计算页码
            if(pageCount%20==0){
                pageCount=pageCount/20;
            }else {
                pageCount=pageCount/20+1;
            }
            for(int i=pageCount;i>0;i--){
                if(i==pageCount){
                    Elements elesNews = docNews.select(".winstyle67214 tbody td a");
                    for (Element e : elesNews) {
                        String underUrl=e.attr("href");
                        underUrl=underUrl.replace("..",url);
//                   包含主网址才能进行操作
                        if(underUrl.contains(url)){
//                        标题
                            Document docNewsLook = Jsoup.parse(PureNetUtil.get(underUrl));
                            String lookNews = docNewsLook.select(".titlestyle67215 ").get(0).text();
                            if(StringUtils.isNotBlank(lookNews))
                                record.setTitle(lookNews);
                            String times = docNewsLook.select(".timestyle67215").get(0).text();
                            if(StringUtils.isNotBlank(times))
                                record.setUsetime(times);
                            String user = docNewsLook.select(".authorstyle67215").text();
                            user=user.replace("&nbsp","");
                            if(StringUtils.isNotBlank(user)){
                                record.setUsername(user);
                            }else {
                                record.setUsername("毕明理");
                            }
                            String num=underUrl.split("/")[5].split(".htm")[0];
                            String scanNum = docNewsLook.select("#n"+num+"").text();
                            System.out.println(underUrl+"------------");
                            String  content = docNewsLook.getElementById("vsb_newscontent").text();
                            if(StringUtils.isNotBlank(content))
                                record.setContent(content);
                            record.setTime(new Date());
                            if (StringUtils.isNotBlank(lookNews)){
                                record.setType(category(lookNews));
                            }else {
                                record.setType(0);
                            }
                            paChongService.insertSelective(record);

                        }
                    }
                }else {
                    String pageUrl=urls+"/"+flag+"/"+i+".htm";
                    Document docNewsPage = Jsoup.parse(PureNetUtil.get(pageUrl));
                    Elements  elesNewsPage = docNewsPage.select(".winstyle67214 tbody td a");
                    for (Element e : elesNewsPage) {
                        String underUrl=e.attr("href");
                        underUrl=underUrl.replace("../..",url);
//                   包含主网址才能进行操作
                        if(underUrl.contains(url)){
                            Document docNewsLook = Jsoup.parse(PureNetUtil.get(underUrl));
                            String lookNews = docNewsLook.select(".titlestyle67215 ").get(0).text();
                            if(StringUtils.isNotBlank(lookNews))
                                record.setTitle(lookNews);
                            String times = docNewsLook.select(".timestyle67215").get(0).text();
                            if(StringUtils.isNotBlank(times))
                                record.setUsetime(times);
                            String user = docNewsLook.select(".authorstyle67215").text();
                            user=user.trim();
                            if(StringUtils.isNotBlank(user)){
                                record.setUsername(user);
                            }else {
                                record.setUsername("毕明理");
                            }
//                            String resultLinks = docNewsLook.select(".authorstyle67215 > span").text();
                            String content="";

                                content = docNewsLook.getElementById("vsb_newscontent").text();

                            if(StringUtils.isNotBlank(content)){
                                record.setContent(content);
                            }
                            record.setTime(new Date());
                            if (StringUtils.isNotBlank(lookNews)){
                                record.setType(category(lookNews));
                            }else {
                                record.setType(0);
                            }
                            paChongService.insertSelective(record);
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return returnDatas;
    }
    @RequestMapping("/listPage")
    public @ResponseBody ReturnDatas list(PaChong paChong, PageBean pageBean, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest){
        ReturnDatas returnDatas=ReturnDatas.getSuccessReturnDatas();
        try {
            try {
                if(pageBean!=null){
                    List<PaChong> paChongs=paChongService.selectByPaChong(paChong);
                    pageBean.setCount(paChongs.size());
                    PageBean pageBeanResult=PageBean.pageBean(pageBean);
                    paChong.setPageBean(pageBeanResult);
                    returnDatas.setPageBean(pageBeanResult);
                }
                List<PaChong> paChongList=paChongService.selectByPaChongPage(paChong);
                returnDatas.setData(paChongList);
            }catch (Exception e){
                return new ReturnDatas(ReturnDatas.ERROR,"操作失败了");
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return returnDatas;
    }
    @RequestMapping("/look")
    public @ResponseBody ReturnDatas look(PaChong paChong, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest){
        ReturnDatas returnDatas=ReturnDatas.getSuccessReturnDatas();
        try {
            String name=httpServletRequest.getParameter("userId");
            if(paChong.getId()==null || StringUtils.isBlank(name)){
                return new ReturnDatas(ReturnDatas.ERROR,"操作失败了");
            }
            try {
                PaChong userResult=paChongService.selectByPrimaryKey(paChong.getId());
                if (userResult!=null && userResult.getType()!=null){
                  addInfo(Integer.valueOf(name),userResult.getType());
                }
                returnDatas.setData(userResult);
            }catch (Exception e){
                return new ReturnDatas(ReturnDatas.ERROR,"操作失败了");
            }
            return returnDatas;

        }catch (Exception e){
            e.printStackTrace();
        }
        return returnDatas;
    }
    public Integer category(String title){
        Integer flag=0;
        if (StringUtils.isNotBlank(title)) {
            if (title.contains("召开"))//会议
                flag = 1;
            if (title.contains("运动会"))//运动
                flag = 2;
            if (title.contains("活动"))//活动
                flag = 3;
            if (title.contains("培训"))//培训会
                flag = 4;
            if (title.contains("荣获"))//荣誉
                flag = 5;
            if (title.contains("思想"))//政治思想
                flag = 6;
        }
        return flag;
    }
    //记录用户喜欢的
    public void addInfo(Integer userId,Integer type){
        MyLikeNews myLikeNews=new MyLikeNews();
        myLikeNews.setUserid(userId);
        myLikeNews.setType(type);
       MyLikeNews myLikeNewsResult= myLikeNewsService.selectByUser(myLikeNews);
       if (myLikeNewsResult!=null){
          myLikeNewsResult.setNum(myLikeNewsResult.getNum()==null?1:myLikeNewsResult.getNum()+1);
          myLikeNewsService.updateByPrimaryKeySelective(myLikeNewsResult);
      }
    }
    @RequestMapping("/myLike")
    public @ResponseBody ReturnDatas myLike(PaChong paChong, PageBean pageBean, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest){
        ReturnDatas returnDatas=ReturnDatas.getSuccessReturnDatas();
        try {
           String userId=httpServletRequest.getParameter("userId");
            if (StringUtils.isBlank(userId)){
                return new ReturnDatas(ReturnDatas.ERROR,"操作失败了！");
            }
            String sort="";
            int i=0;
            MyLikeNews myLikeNews=new MyLikeNews();
            myLikeNews.setUserid(Integer.valueOf(userId));
            List<MyLikeNews> myLikeNewsList=myLikeNewsService.selectByList(myLikeNews);
            if (myLikeNewsList!=null && myLikeNewsList.size()>0){
                for (MyLikeNews data:myLikeNewsList){
                         i++;
                       if (i<=3){
                           if (i==1){
                               if (data.getNum().intValue()==0){
                                   break;
                               }
                               sort=sort+"type ="+data.getType();
                           }else {
                               sort=sort+" or type ="+data.getType();
                           }
                       }else {
                           break;
                       }
                  }
            }
                if (StringUtils.isNotBlank(sort)){
                    paChong.setSort(sort);
                if(pageBean!=null){
                    PageBean pageBeanResults=new PageBean();
                    pageBeanResults.setPageSize(1000000000);
                    paChong.setPageBean(new PageBean());
                    List<PaChong> paChongs=paChongService.selectByType(paChong);
                    pageBean.setCount(paChongs.size());
                    PageBean pageBeanResult=PageBean.pageBean(pageBean);
                    paChong.setPageBean(pageBeanResult);
                    returnDatas.setPageBean(pageBeanResult);
                }
                List<PaChong> paChongList=paChongService.selectByType(paChong);
                returnDatas.setData(paChongList);
                }
        }catch (Exception e){
            e.printStackTrace();
        }
        return returnDatas;
    }

}
